package net;


import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpCli {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;
    public UdpCli(String serverIp,int serverPort) throws SocketException {
        socket= new DatagramSocket();
        this.serverPort =serverPort;
        this.serverIp = serverIp;
    }
    public void start() throws IOException {
        System.out.println("客户端启动!");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.print("->");
            //从控制台里接收请求,发送请求
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(this.serverIp),this.serverPort);
            socket.send(requestPacket);
            //接收响应数据包,并解析

            DatagramPacket responsePacket= new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }
}
